package Thread;

import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

public class ReadAndWrite {
    private ReadWriteLock readWriteLock=new ReentrantReadWriteLock();
    public void read(){
        readWriteLock.readLock().lock();
        System.out.println("read------start----"+Thread.currentThread().getName());
        try {
            Thread.sleep(20);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("read------end----"+Thread.currentThread().getName());
        readWriteLock.readLock().unlock();
    }
    public void write(){
        readWriteLock.writeLock().lock();
        System.out.println("write------start----"+Thread.currentThread().getName());
        try {
            Thread.sleep(20);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("write------end----"+Thread.currentThread().getName());
        readWriteLock.writeLock().unlock();
    }
}

class TestReadAndWrite{

    public static void main(String[] args) {
        ReadAndWrite readAndWrite=new ReadAndWrite();
        for(int i=0;i<3;i++){
            new Thread(
                    ()->{
                        readAndWrite.write();
                    }
            ).start();
        }
        for(int i=0;i<3;i++){
            new Thread(new Runnable(){
                @Override
                public void run() {
                    readAndWrite.read();
                }
            }).start();
        }

    }
}






















